package fetzu.app;

import java.io.IOException;
import java.util.TimeZone;

import org.apache.commons.io.IOUtils;

public class TimeZoneManager {

	static String getJavaTimeZoneId() {
		return TimeZone.getDefault().getID().intern();
	}

	static void setSystemTimeZone(String timezoneId) {
		// Java's TimeZone.setDefault() doesn't work because it changes only the
		// JVM's tz and not the system's

		String osName = System.getProperty("os.name").intern();
		String osVersion = System.getProperty("os.version").intern();

		if (osName == "Mac OS X")
			setMacTZ(osVersion, timezoneId);
		else
			throw new RuntimeException("os not yet implemented");
	}

	private static void setMacTZ(String osVersion, String timezoneId) {
		String commandPath;
		if (osVersion.startsWith("10.5")) {
			commandPath = "/usr/sbin/systemsetup";
		} else if (osVersion.startsWith("10.4")) {
			commandPath = "/System/Library/CoreServices/RemoteManagement/ARDAgent.app/Contents/Support/systemsetup";
		} else
			throw new RuntimeException("Mac OS X " + osVersion
					+ " not supported");

		String[] commands = new String[] { commandPath, "-settimezone",
				timezoneId };

		try {
			Process child = Runtime.getRuntime().exec(commands);
			String result = IOUtils.toString(child.getInputStream());
			System.out.println(result);
			boolean success = result.startsWith("Set TimeZone: " + timezoneId);
			// if that succeeds, update the current JVM's tz too
			if (success)
				TimeZone.setDefault(TimeZone.getTimeZone(timezoneId));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new RuntimeException("failed to change timezone");
		}
	}

}
